﻿using System.IO;
using GarboDev;
using CJToolkit.Util;

namespace GBAExtentionLib
{
    public class GameSaveHandler
    {
        public static void Save(Stream stream,MemorySave save)
        {
            int lengh = save.EWRam.Length;
            stream.Write(lengh.GetColorByte(), 0, 4);
            stream.Write(save.EWRam, 0, lengh);
            lengh = save.IWRam.Length;
            stream.Write(lengh.GetColorByte(), 0, 4);
            stream.Write(save.IWRam, 0, lengh);
            lengh = save.IORam.Length;
            stream.Write(lengh.GetColorByte(), 0, 4);
            stream.Write(save.IORam, 0, lengh);
            lengh = save.OamRam.Length;
            stream.Write(lengh.GetColorByte(), 0, 4);
            stream.Write(save.OamRam, 0, lengh);
            lengh = save.PaletteRam.Length;
            stream.Write(lengh.GetColorByte(), 0, 4);
            stream.Write(save.PaletteRam, 0, lengh);
            lengh = save.VideoRam.Length;
            stream.Write(lengh.GetColorByte(), 0, 4);
            stream.Write(save.VideoRam, 0, lengh);
            stream.Flush();
        }

        public static MemorySave Load(Stream stream)
        {
            var save = new MemorySave();
            var lengthBytes = new byte[4]; 
            stream.Read(lengthBytes, 0, 4);
            int length = lengthBytes.GetColorInteger();
            save.EWRam = new byte[length];
            stream.Read(save.EWRam, 0, length); 
            lengthBytes = new byte[4]; 
            stream.Read(lengthBytes, 0, 4);
            length = lengthBytes.GetColorInteger();
            save.IWRam = new byte[length];
            stream.Read(save.IWRam, 0, length);
            lengthBytes = new byte[4]; 
            stream.Read(lengthBytes, 0, 4);
            length = lengthBytes.GetColorInteger();
            save.IORam = new byte[length];
            stream.Read(save.IORam, 0, length);
            lengthBytes = new byte[4];
            stream.Read(lengthBytes, 0, 4);
            length = lengthBytes.GetColorInteger();
            save.OamRam = new byte[length];
            stream.Read(save.OamRam, 0, length);
            lengthBytes = new byte[4];
            stream.Read(lengthBytes, 0, 4);
            length = lengthBytes.GetColorInteger();
            save.PaletteRam = new byte[length];
            stream.Read(save.PaletteRam, 0, length);
            lengthBytes = new byte[4];
            stream.Read(lengthBytes, 0, 4);
            length = lengthBytes.GetColorInteger();
            save.VideoRam = new byte[length];
            stream.Read(save.VideoRam, 0, length);
            return save;
        }
    }
}
